package com.lzj.servlet;

import com.lzj.dao.UserDao;
import com.lzj.dao.impl.UserDaoImpl;
import com.lzj.entity.ShoppCart;
import com.lzj.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @autor:lzj
 * @date:2021/12/8
 */
public class AddCartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String skuId = req.getParameter("skuId");
        String url = req.getParameter("url");
        String name = req.getParameter("name");
        String price = req.getParameter("price");
        String specification = req.getParameter("specification");
        String count = req.getParameter("count");
        String userId = req.getParameter("userId");
        double totalPrice= Double.valueOf(price)*Integer.valueOf(count);

        UserServiceImpl userService = new UserServiceImpl();
        UserDao userDao = new UserDaoImpl();
        userService.setUserDao(userDao);

        List<ShoppCart> shoppCarts1= (List<ShoppCart>) req.getSession().getAttribute("shoppCarts");
        boolean flag=false;//默认不存在该商品
        int count1 = 0;
        for (ShoppCart shoppCart : shoppCarts1) {//判断该用户购物车内是否存在该商品
            if(shoppCart.getSkuId()==Integer.valueOf(skuId)&&shoppCart.getUserId()==Integer.valueOf(userId)){
                flag=true;
                count1=shoppCart.getCount();
            }
        }

        if(flag==true){//更新购物车内该商品的数量和总价
            userDao.updateShoppCart(count1+Integer.valueOf(count),Double.valueOf(price)*(count1+Integer.valueOf(count)),Integer.valueOf(skuId),Integer.valueOf(userId));
        }else{//将该商品添加到购物车内
            ShoppCart shoppCart=new ShoppCart(Integer.valueOf(skuId),url,name,Double.valueOf(price),specification,Integer.valueOf(count),totalPrice,Integer.valueOf(userId));
            int i = userService.addShoppCart(shoppCart);
        }
        //更新session的信息，数据更新
        List<ShoppCart> shoppCarts = userService.queryShoppCart(Integer.valueOf(userId));
        req.getSession().setAttribute("shoppCarts",shoppCarts);
        resp.sendRedirect("cart.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
